package com.demo.service.Impl;

import com.demo.mapper.OrderMapper;
import com.demo.model.Order;
import com.demo.service.OrderService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

/**
 * @author Kevin
 * @date 2020/4/21 20:36
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderMapper orderMapper;

    @Override
    public List<OrderVo> weeklyCount() {
        // 这里是统计各个商品在一周的各天内的销量
        List<Order> orders = orderMapper.weeklyCount();
        // 这里可以用CurrentHashMap优化
        HashMap<String, OrderVo> orderKind = new HashMap<>();

        for (Order order: orders) {
            // 如果该商品类不存在
            if (!orderKind.containsKey(order.getName())) {
                // 创建该商品类
                OrderVo temp = new OrderVo(order.getName());
                // 使得商品类存在
                orderKind.put(order.getName(), temp);
            }
            // 处理订单，计算商品类在某日的销量
            orderKind.get(order.getName()).data[order.getDay()-1] += order.getNum();
        }
        //返回Echarts用的Series数组
        //return (List<OrderVo>) orderKind.values();        //Collections硬转List，这样看网上好像是不行的
        return new ArrayList<OrderVo>(orderKind.values());  //将collection转为object数组返回，里面调用了toArray
    }

    // 折线图的返回，代替Series
    public class OrderVo implements Serializable {
        public String name;
        // 这样初始化为0了，这里可以用Atom原子类优化
        public int[] data;
        public String type = "line";
        public String stack = "总量";

        public OrderVo(String name) {
            this.name = name;
            data = new int[7];
        }
    }
}
